<?php

namespace Blockgolde\HyperfBusinessWrapper\Utils;

use RecursiveDirectoryIterator;
use RecursiveFilterIterator;
use RecursiveIteratorIterator;

class DirScan
{
    /**
     * @var RecursiveIteratorIterator $_dirIterator
     */
    private RecursiveIteratorIterator $_dirIterator;

    /**
     * @param string $path
     * @param string $filter
     */
    public function __construct(string $path, string $filter = '')
    {
        // 设置当前scan的目录
        $directory = new RecursiveDirectoryIterator($path);

        // 实例化迭代器
        if ($filter && is_subclass_of($filter, RecursiveFilterIterator::class)) {
            $directory = new $filter($directory);
        }

        // 实例化包装器
        $this->_dirIterator = new RecursiveIteratorIterator($directory);
    }

    /**
     * @return array
     *
     * 列出目录下文件
     */
    public function listFile(): array
    {
        return array_map(function ($fileInfo) {
            return [
                'pathname'  => $fileInfo->getPathname(),
                'ctime'     => $fileInfo->getCTime(),
                'extension' => $fileInfo->getExtension(),
                'filename'  => $fileInfo->getFilename(),
                'path'      => $fileInfo->getPath(),
                'size'      => $fileInfo->getSize(),
            ];
        }, iterator_to_array($this->_dirIterator));
    }
}
